import {
	vibrateLong
} from '@/util/util.js';

export class Push {
	constructor(args) {
		this.pushId = null;
		this.timer = null;
		this.fn = args.fn;
		this.platform = null;

		this.getPlatform();
	}
	getPlatform() {
		uni.getSystemInfo({
			success: (e) => {
				this.platform = e.platform;
			}
		})
	}
	
	_handlePushReceive(msg) {
		if (msg.payload && msg.payload.message_type == 20 && msg.payload.message_url == 'video_call') {
			vibrateLong();
		
			uni.showModal({
				title: '提示',
				content: `${msg.payload.message_content}`,
				success: (res) => {
					let pages = getCurrentPages();
					let page = pages[pages.length - 1];
		
					if (page.route == 'pages/Agora/index') {
						uni.$emit('alert.call.joinChannel');
					} else {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/Agora/index'
							})
						} else if (res.cancel) {
		
						}
					}
				}
			});
		} else {
		
		}
	}
	
	_handlePushClick(msg) {
		
	}
	
	bindEvent() {
		plus.push.addEventListener('click', this._handlePushClick.bind(this), false);
		plus.push.addEventListener('receive',this._handlePushReceive.bind(this), false);
	}

	async cycle() {
		if (this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}
		let clientid = await this.getClientid();

		if (clientid) {
			this.pushId = clientid;
			this.fn(this.pushId);
		} else {
			this.timer = setTimeout(this.cycle.bind(this), 1000);
		}
	}

	createMessage(content, payload, option) {
		plus.push.createMessage(content, payload, option);
	}

	getAllMessage() {
		let messages = plus.push.getAllMessage();

		return messages;
	}

	getClientid() {
		return new Promise(async (resolve, reject) => {
			plus.push.getClientInfoAsync((info) => {
				let cid = info.clientid; //客户端标识
				resolve(cid);
			}, (e) => {})
		})
	}
}
